package gsw.tool.pluggable.hook.hook;

import android.os.Handler;

import java.lang.reflect.Field;

import gsw.tool.pluggable.hook.handler.BaseHandlerClass;
import gsw.tool.pluggable.hook.handler.HandlerMH;

/**
 * Hook当前ActivityThread的mH，用来修改luanchActiity消息的回调，因为之前将跳转目标设为代理组件，所以现在需要将跳转目标还原。
 * 注意：开启新进程打开插件时，需要对新进程的ActivityThread的mH进行Hook。
 */
public class HookMH extends BaseHook {

    @Override
    protected BaseHandlerClass createHookHandle() {
        return null;
    }

    @Override
    public void onInit(ClassLoader classLoader) {
        try {
            Class<?> forName = Class.forName("android.app.ActivityThread");
            Field currentActivityThreadField = forName.getDeclaredField("sCurrentActivityThread");
            currentActivityThreadField.setAccessible(true);
            //获取系统的ActivityTread的sCurrentActivityThread属性
            Object activityThreadObj = currentActivityThreadField.get(null);

            Field handlerField = forName.getDeclaredField("mH");
            handlerField.setAccessible(true);
            //获取sCurrentActivityThread的mH对象
            Handler mH = (Handler) handlerField.get(activityThreadObj);

            Field callbackField = Handler.class.getDeclaredField("mCallback");
            callbackField.setAccessible(true);
            //使用自定义的mCallback对象替换mH的mCallback属性
            callbackField.set(mH, new HandlerMH(mH));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
